param(
    [Parameter(Mandatory=$true)]
    [string]$Path,
    
    [Parameter(Mandatory=$false)]
    [string]$OutputPath
)

try {
    # Create Word Application COM object
    $word = New-Object -ComObject Word.Application
    $word.Visible = $false

    # Resolve full input path
    $inputPath = (Resolve-Path $Path).Path

    # Set output path
    if (-not $OutputPath) {
        $OutputPath = [System.IO.Path]::ChangeExtension($inputPath, "docx")
    }

    # Open document and save as DOCX
    $doc = $word.Documents.Open($inputPath)
    $doc.SaveAs([ref]$OutputPath, [ref]16)  # wdFormatDocumentDefault = 16
    $doc.Close()

    Write-Host "Successfully converted '$Path' to '$OutputPath'"
}
catch {
    Write-Error "Error during conversion: $_"
}
finally {
    # Clean up COM object
    if ($word) {
        $word.Quit()
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
    }
}